package com.yantong.controller.centre;

import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.*;
import com.yantong.service.CentreService;
import com.yantong.constant.MemberType;
import com.yantong.constant.PayStatus;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.service.OrderService;
import com.yantong.service.MemberService;
import com.yantong.service.RegCommanderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author xiangyi
 * @version V1.0.0
 * @Description:
 * Copyright: Copyright (c) 2018
 * Company: 未审核
 * @date 2018年9月4日 上午10:04:23
 * @since 3.0
 */
@Controller
@RequestMapping("/noCheck/manage")
public class NoCheckCommanderController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(NoCheckCommanderController.class);

	private static final String prefix = "commander/manage";

	@Autowired
	private RegCommanderService regCommanderService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private OrderService orderService;

//	@Autowired
//	private CarXqService carXqService;
	@Autowired
	private CentreService centreService;

	/**
	 * 未审核列表界面
	 *
	 * @return
	 */
	@GetMapping()
	@RequiresPermissions("noCheck:manage:manage")
	public String noCheckCommanders(Model model) {
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/noCheckCommanders";
	}


	/**
	 * 未审核列表
	 *
	 * @param listMemberParams
	 * @param member
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("noCheck:manage:manage")
	public PageUtils<Member> noCheckCommander(ListMemberParams listMemberParams, Member member, int offset, int limit) {
		if (listMemberParams.getCentreId() == null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		return regCommanderService.noCheckCommander(listMemberParams, member, offset, limit);
	}

	/**
	 * 设置门店批次
	 *
	 * @param id
	 * @param model
	 * @return
	 * @author xiangyi
	 * @date 2018年9月5日 上午11:49:39
	 */
	@RequiresPermissions("noCheck:manage:edit")
	@GetMapping("/batchEdit/{id}")
	public String batchEdit(@PathVariable Long id, Model model) {
		model.addAttribute("member", memberService.getByKey(id));
		return prefix + "/batchEdit";
	}

	/**
	 * 门店批次更新
	 *
	 * @param member
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:edit")
	@PostMapping("/batchUpdate")
	public ResultVo batchUpdate(Member member) {
		if (member == null || member.getId() == null) {
			return ResultVo.error();
		}
		if (memberService.updateMember(member) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量设置门店批次
	 *
	 * @param ids
	 * @param model
	 * @return
	 * @author xiangyi
	 * @date 2018年9月5日 下午5:13:12
	 */
	@RequiresPermissions("noCheck:manage:edit")
	@GetMapping("/batchEdits/{ids}")
	public String batchEdit(@PathVariable String ids, Model model) {
		model.addAttribute("ids", ids);
		return prefix + "/batchEdits";
	}

	/**
	 * 门店批次更新
	 *
	 * @param ids
	 * @param teamNum
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:edit")
	@PostMapping("/batchUpdates")
	public ResultVo batchUpdates(String ids, Integer teamNum) {
		if (StringUtils.isEmpty(ids) || teamNum == null) {
			return ResultVo.error();
		}
		if (regCommanderService.batchUpdates(ids, teamNum) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量审核并开通
	 *
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:examine")
	@PostMapping("/batchExamine")
	public ResultVo batchExamine(String ids) {
		if (StringUtils.isEmpty(ids)) {
			return ResultVo.error();
		}
		if (regCommanderService.batchExamine(ids, MemberType.COMMANDER.getCode()) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 查看详情
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("noCheck:manage:detail")
	@GetMapping("/detail/{id}")
	public String detail(@PathVariable Long id, Model model) {
		Member member = memberService.getDetail(id);
		Order order = new Order();
		order.setMid(id);
		Integer orderSum = orderService.countByOrder(order);
		member.setOrderSum(orderSum);
		member.setLat(member.getLng() + "," + member.getLat());
		IsteamDesc isteamDesc = regCommanderService.getIsteamDesc(member.getIsteamDesc());
		member.setTeamDesc(isteamDesc);
		model.addAttribute("member", member);
		return prefix + "/noCheckDetail";
	}

	/**
	 * 查看详情-提交
	 *
	 * @param member
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:detail")
	@PostMapping("/noCheckUpdate")
	public ResultVo noCheckUpdate(Member member) {
		return memberService.noCheckUpdate(member);
	}

	/**
	 * 查看详情-保存资料
	 *
	 * @param member
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:detail")
	@PostMapping("/saveZlUpdate")
	public ResultVo saveZlUpdate(Member member) {
		if (member == null || member.getId() == null) {
			return ResultVo.error();
		}
		if (StringUtils.isEmpty(member.getLat())) {
			member.setLng(null);
			member.setLat(null);
		} else {
			String[] str = member.getLat().split(",");
			if (str != null && str.length >= 2) {
				member.setLng(str[0]);
				member.setLat(str[1]);
			} else {
				member.setLng(null);
				member.setLat(null);
			}
		}
		member.setIsteam(null);//保存资料时,不更新状态
		if (memberService.updateMember(member) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 门店拒绝
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("noCheck:manage:detail")
	@GetMapping("/reject/{id}")
	public String reject(@PathVariable String id, Model model) {
		model.addAttribute("id", id);
		return prefix + "/reject";
	}

	/**
	 * 拒绝门店-提交
	 *
	 * @param member
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("noCheck:manage:detail")
	@PostMapping("/rejectUpdate")
	public ResultVo rejectUpdate(Member member) {
		if (member == null || member.getId() == null) {
			return ResultVo.error();
		}
		member.setIsteam(MemberType.NORMAL.getCode());//拒绝,变为普通会员
		member.setIsCheck(1);//拒绝 修改是否拒绝状态
		member.setRefTime(new Date());
		if (memberService.updateMember(member) < 1) {
			return ResultVo.error();
		} else {
			//退款
			Order order = orderService.getTeamOrder(member.getId());
			if (order != null && PayStatus.PAY_SUCCESS.getCode() == order.getPaystatus()) {
				String sn = DateUtils.format(new Date(), "ddHHmmss");
				String refundNo = "REFUND".concat(sn);
				Centre centre = centreService.getByKey(order.getCentreId());
				try {
					YFZPayutil.refundApply(order.getPayprice(), order.getOutTradeNo(), centre, refundNo, "", null);
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}
		}
		return ResultVo.ok();
	}

	/**
	 * 未审核列表-导出
	 *
	 * @param response
	 * @param listMemberParams
	 * @param member
	 */
	@RequiresPermissions("noCheck:manage:export")
	@GetMapping("/exportNoCheck")
	public void exportNoCheck(HttpServletResponse response, ListMemberParams listMemberParams, Member member) {
		List<List<Object>> resultData = new ArrayList<>();
		String[] head = {"门店ID", "门店昵称", "门店姓名", "门店手机", "推荐门店", "开通时间", "保证金", "团员数量", "区", "门店地址", "小区", "经纬度"/*,"所属路线"*/, "余额", "门店批次", "申请统计"};
		resultData.add(0, Arrays.asList(head));
		if (listMemberParams.getCentreId() == null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		List<Member> list = regCommanderService.noCheckCommander(listMemberParams, member);
		if (CollectionUtils.isNotEmpty(list)) {
			for (Member mem : list) {
				List<Object> row = new ArrayList<>();
				row.add(mem.getId());
				row.add(mem.getNickname() != null ? mem.getNickname() : "");
				row.add(mem.getRealname() != null ? mem.getRealname() : "");
				row.add(mem.getMobile() != null ? mem.getMobile() : "");
				row.add(mem.getUpTeamname() != null ? mem.getUpTeamname() : "");
				row.add(mem.getCheckTime() != null ? DateUtils.format(mem.getCheckTime(), "yyyy-MM-dd HH:mm:ss") : "");
				row.add(mem.getBondmoney() != null ? mem.getBondmoney() : "");
				row.add("");
				row.add(mem.gettArea() != null ? mem.gettArea() : "");
				String adress = "";
				if (mem.gettProvince() != null) adress += mem.gettProvince();
				if (mem.gettCity() != null) adress += mem.gettCity();
				if (mem.gettArea() != null) adress += mem.gettArea();
				if (mem.gettXiaoqu() != null) adress += mem.gettXiaoqu();
				if (mem.gettShopname() != null) adress += mem.gettShopname();
				row.add(adress);
				row.add(mem.gettXiaoqu() != null ? mem.gettXiaoqu() : "");
				String jxd = "";
				if (mem.getLng() != null) jxd += mem.getLng() + ",";
				if (mem.getLat() != null) jxd += mem.getLat();
				row.add(jxd);
//				CarXq carXq = carXqService.getCarXqByXqName(mem.gettXiaoqu());
                 /*if(carXq != null){
                     Car car = psPersonService.getByKey(carXq.getCarId());
                     if(car != null){
                         row.add(car.getUsername());
                     }else{
                         row.add("");
                     }
                 }else{
                     row.add("");
                 }*/
				row.add(mem.getCredit2() != null ? mem.getCredit2() : "");
				row.add(mem.getTeamNum() != null && mem.getTeamNum() > 0 ? mem.getTeamNum() : "最新批次");
				row.add(mem.getsTime() != null ? DateUtils.format(mem.getsTime(), "yyyy-MM-dd HH:mm:ss") : "");
				resultData.add(row);
			}
			String fileName = "未审核列表_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
			try {
				ExcelHelper.exportExcel(response, fileName, "未审核列表", resultData);
			} catch (IOException e) {
				logger.info("export NoCheck error:{}", e.getMessage());
			}
		}
	}

}
